<?php

/**
 * 商城搜索程序
 * ============================================================================
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
*/

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
assign_template();//读取通用变量
// 初始化搜索变量
$string=!empty($_GET['encode'])   ?trim($_GET['encode'])     : '';//用户输入的关键词
if(!empty($string)){
    $string =base64_decode($string);
    $string =unserialize($string);
    $keyword =$string['keywords'];
}

$keyword=!empty($_REQUEST['keywords'])   ? trim($_REQUEST['keywords'])     : $keyword;//用户输入的关键词
$area_id=!empty($_SESSION['area_id'])    ? intval($_SESSION['area_id'])    :  1;//获取区域ID  
$default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC';
$default_sort_order_type   = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update');
$sort  = (isset($_REQUEST['sort'])  && in_array(trim(strtolower($_REQUEST['sort'])), array('click_count', 'shop_price', 'buy_sum'))) ? trim($_REQUEST['sort'])  : $default_sort_order_type;
$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : 'ASC';
$size  =10;
$page  =!empty($_REQUEST['page'])    ? intval($_REQUEST['page'])    :  1;//获取页码


if(!empty($keyword)){
        $arr = array();
        /* 检查关键字中是否存在于词库 */
        $arr        = sc_word($_REQUEST['keywords']);
        $arr        = $arr ? array_values($arr) : array($_REQUEST['keywords']);
        $operator   = " OR ";
        $keyword_arr = $arr;
        $keywords = 'AND ((';
        $goods_ids = array();
        foreach ($arr AS $key => $val)
        {
            $val        = mysql_like_quote(trim($val));
            $sc_dsad    = $_REQUEST['sc_ds'] ? " OR goods_desc LIKE '%$val%'" : '';
            if($key != 0) $keywords .= " AND ";
            $keywords .= " CONCAT(goods_name,keywords,goods_desc) LIKE '%$val%' ";
            $db->autoReplace($ecs->table('keywords'), array('date' => local_date('Y-m-d'),
                'searchengine' => 'ecshop', 'keyword' => addslashes(str_replace('%', '', $val)), 'count' => 1), array('count' => 1));
        }

        $keywords .= ") OR keywords LIKE '%$_REQUEST[keywords]%') ";


            /* 获得符合条件的商品总数 */
        $sql   = "SELECT COUNT(*) FROM " .$ecs->table('goods'). " AS g ".
        "WHERE g.warn_number = 1 AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 $attr_in ".
        $keywords ;
        $count = $db->getOne($sql);
        //获取符合条件的商品
        $sql = 'SELECT g.goods_id,g.shopall_note, g.goods_name, g.shop_price, g.market_price, g.preferential_price2, g.preferential_price5, g.click_count, g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_thumb, g.goods_img, g.goods_type, g.is_new, g.is_taodan, g.is_taobao, ' . 
        "(select sum(goods_number) from " . $GLOBALS['ecs']->table('order_goods') . " WHERE goods_id = g.goods_id ) AS buy_sum " . 
        "FROM " . $GLOBALS['ecs']->table('goods'). " AS g ". 
        "WHERE g.warn_number = 1 AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.cat_id != 210 ".
        $keywords .
        "ORDER BY $sort $order";
        $res = $db->SelectLimit($sql, $size, ($page - 1) * $size);
        $arr = array();
    while ($row = $db->FetchRow($res))
    {
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else
        {
            $promote_price = 0;
        }
        // $shop_price=empty($promote_price)?$row['shop_price']:$promote_price;
        $arr[$row['goods_id']]['goods_id']      = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']    = $row['goods_name'];
        preg_match_all("/./u", $_REQUEST['keywords'], $preg_match_all);
        preg_match_all("/./u", $row['goods_name'], $preg_match_alls);
        foreach($preg_match_alls[0] AS $key=>$value){
            if(in_array($value,$preg_match_all[0])&&trim($value)){
                $preg_march[] = '<span class="red">'.$value.'</span>';
            }else{
                $preg_march[]=$value;
            }
        }
        $arr[$row['goods_id']]['goods_name'] = implode('',$preg_march);
        $arr[$row['goods_id']]['goods_name'] = !empty($row['shopall_note'])?$row['shopall_note']:$arr[$row['goods_id']]['goods_name'];
        unset($preg_march);
        $arr[$row['goods_id']]['shop_price']           = price_format($row['shop_price']);
        if($row['market_price'] > 0){//存在市场价时的市场价
            $arr[$row['goods_id']]['market_price']     = price_format($row['market_price']);
        }else{//不存在市场价时的市场价
            $arr[$row['goods_id']]['market_price']     = price_format(sprintf('%.1f',$row['shop_price']*1.2));
        }
        $arr[$row['goods_id']]['preferential_price2']  = ($row['preferential_price2'] > 0) ? price_format($row['preferential_price2']) : ''; //第二梯度价格
        $arr[$row['goods_id']]['preferential_price5']  = ($row['preferential_price5'] > 0) ? price_format($row['preferential_price5']) : ''; //第五梯度价格
        $arr[$row['goods_id']]['promote_price']        = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$row['goods_id']]['goods_thumb']   = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['url']           = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);
        $arr[$row['goods_id']]['click_count']   = $row['click_count'];
        $arr[$row['goods_id']]['is_new']        = $row['is_new'];
        $arr[$row['goods_id']]['is_taodan']           = $row['is_taodan'];
        $arr[$row['goods_id']]['is_taobao']           = $row['is_taobao'];
    }
// 赋值变量
    $position = assign_ur_here(0, $ur_here . ($_REQUEST['keywords'] ? '_' . $_REQUEST['keywords'] : ''));
    $smarty->assign('page_title', $position['title']);    // 页面标题
    $smarty->assign('top_title', $keyword);    // 页面标题
    $smarty->assign('ur_here',    $position['ur_here']);  // 当前位置
    $smarty->assign('script_name',    'search');  // 当前文件名
    $smarty->assign('keywords',    trim($_REQUEST['keywords']));  // 当前关键字
    $smarty->assign('goods_list', $arr);
//分页
    $page_count = $count > 0 ? intval(ceil($count / $size)) : 1;//总页码
    $page_prev  = ($page > 1) ? $page - 1 : 1;//上一页
    $page_next  = ($page < $page_count) ? $page + 1 : $page_count;//下一页
    $url_format = 'search.php?keywords='.$keyword.'&sort='.$sort.'&order='.$order.'&page=';//页码前缀          
        for ($i=1;$i<=$page_count;++$i)
    {
        $pager['wap_page_number'][$i] = $url_format.$i;
    }
    $pager['page_first'] = ($page - $_offset > 1 && $_pagenum < $page_count) ? $url_format . 1 : '';
    $pager['page_prev']  = ($page > 1) ? $url_format . $page_prev : '';
    $pager['page_next']  = ($page < $page_count) ? $url_format . $page_next : '';
    $pager['page_last']  = ($_to < $page_count) ? $url_format . $page_count : '';
    $pager['page']=$page;
    $pager['order']=$order;
    $pager['sort']=$sort;
    $pager['page_count']=$page_count;
    $smarty->assign('pager', $pager);
}

/* 获取产品列表底部广告 */
$ad_1=get_ad(11);//产品列表底部广告
$smarty->assign('ad_1', $ad_1);

$page_address=$page<4?0:($page-3)*44;
$smarty->assign('page_address', $page_address);
$smarty->assign('page_now', $page);
$smarty->assign('footer', get_footer());
$smarty->display('search.dwt');


// 返回分词函数
function sc_word($keywords)
{
        $word = word('word');
        if($keywords){
            for($i=0;$i<mb_strlen($keywords,'UTF8');$i++){
                for ($j=$i+1; $j <= mb_strlen($keywords,'UTF8'); $j++) { 
                    $k = mb_substr($keywords,$i,$j-$i,'UTF8');
                    if(in_array($k,$word)){
                        $word_arr[] = $k;
                    }
                }
            }
            
        }
        $len = count($word_arr);
        for($i=0;$i<$len;$i++){
            for($j=$i+1;$j<$len;$j++){
                if(mb_strlen($word_arr[$i],'UTF8')<mb_strlen($word_arr[$j],'UTF8')){
                    $tmp=$word_arr[$j];
                    $word_arr[$j]=$word_arr[$i];
                    $word_arr[$i]=$tmp;
                }
            }
        }
    
        return $word_arr;
}

/**
 * 获得广告位
 *
 * @access  private
 * @return  array
 */
function get_ad($position_id = 0){
        if(!$position_id) return false;
        $position_id = intval($position_id);
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('ad') . " WHERE position_id = '$position_id' ORDER BY ad_name ASC ";
        return $GLOBALS['db']->getAll($sql);
    }

?>